module baremetal.hook;

import std.traits;
import baremetal.malloc;
import baremetal.stdlib;


/**
* 用于创建对象的函数
* Params:
*   T = 对象类型, 可以是类, 结构体, 联合体
* Returns:
*   T类型的对象
* example:
---
alias C = struct { int a; int b;};
C* c = CreateObject!(C)();
---
* Bugs: 
* 未执行构建函数
*/
T CreateObject(T)() if (is(T == class)) //类
{
	//pragma(msg,"Clock:",__traits(allMembers, T));
	//pragma(msg,"Clock:",__traits(classInstanceSize, T));
    //pragma(msg,"Clock:",__traits(getPointerBitmap, T));
    //enum size_t len1 = __traits(classInstanceSize, T);
    //enum size_t len2 = __traits(getPointerBitmap, T)[0];

	const void[] initSym = __traits(initSymbol, T);

    size_t len = initSym.length;
    //size_t len = len2;
    
//    auto vvf = initSym.ptr;

	void* ptr = malloc(len);
    //memcpy(ptr, vvf, len);
    
    ptr[0..initSym.length] = initSym[];

    return cast(T)ptr;
};

S* CreateObject(S)() if (is(S == struct) || is(S == union)) //结构体 & 联合体
{
    const void[] initSym = __traits(initSymbol, S);
    void* ptr = malloc(initSym.length);
    ptr[0..initSym.length] = initSym[];
    return cast(S*)ptr;
}

/// 释放对象
void DestroyObject(T)(ref T obj)
{
    scope(exit) obj = null;             // 销毁指针
    free(cast(void*)obj);
}
